package com.wmyg.antifake.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.image.BufferedImage;
import java.util.HashMap;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-21
 */
public class CodeImageUtil {

    public static BufferedImage createQRPic(String qR, Integer level) {
        BufferedImage image = null;
        int width = 300;
        int height = 300;
        String format = "jpeg";
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "ASCII");
        switch (level) {
            case 1:
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
                break;
            case 0:
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
                break;
            case 3:
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
                break;
            case 2:
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                break;
            default:
                break;
        }
        hints.put(EncodeHintType.MARGIN, 1);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(qR, BarcodeFormat.QR_CODE, width, height, hints);
            image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

}
